<template>
    <MainLayout>
    <div class="ai-chat-page">
      <h2>AI-小布</h2>
      <!-- 聊天历史记录展示区域 -->
      <div ref="chatDialog" class="chat-dialog">
        <div v-for="(message, index) in chatMessages" :key="index" 
             :class="['message', message.type]">
          {{ message.content }}
        </div>
      </div>
      <div class="input-container">
        <el-input
          v-model="userInput"
          placeholder="请输入学术问题"
          @keyup.enter="sendMessage"
          clearable
        ></el-input>
        <el-button type="primary" @click="sendMessage">发送</el-button>
      </div>
    </div>
  </MainLayout>
</template>

<script>
import { ElInput, ElButton } from 'element-plus';
import MainLayout from '@/layouts/MainLayout.vue'

export default {
  components: { ElInput, ElButton,MainLayout },
  data() {
    return {
      userInput: '',
      chatMessages: [],
      eventSource: null,
      retryCount: 3
    };
  },
  methods: {
    updateAiMessage(content) {
      const lastIndex = this.chatMessages.length - 1;
      if (this.chatMessages[lastIndex]?.type === 'ai') {
        // 修复Vue3响应式更新问题
        this.chatMessages[lastIndex].content = content;
        this.chatMessages = [...this.chatMessages]; // 触发数组响应式更新
      } else {
        this.chatMessages.push({
          type: 'ai',
          content: content
        });
      }
      this.scrollToBottom();
    },
    sendMessage() {
      if (!this.userInput.trim()) return;

      this.chatMessages.push({
        type: 'user',
        content: this.userInput
      });
      this.scrollToBottom();

      // 根据新接口调整请求参数
      const question = encodeURIComponent(this.userInput);
      this.eventSource = new EventSource(`http://localhost:8090/ai/ai_generate/sse?question=${question}`);

      // 添加编码处理解决乱码问题
      const decoder = new TextDecoder('utf-8');
      let aiResponse = '';
      
      this.eventSource.onopen = () => {
        console.log('SSE连接已建立');
      };

      this.eventSource.onmessage = (event) => {
        // 修复TextDecoder参数类型问题
        if (event.data) {
          const encoder = new TextEncoder();
          const uint8Array = encoder.encode(event.data);
          const decodedData = decoder.decode(uint8Array);
          aiResponse += decodedData;
          this.updateAiMessage(aiResponse);
        }
      };

      this.eventSource.onerror = (error) => {
        if (this.retryCount-- > 0) {
          setTimeout(() => this.sendMessage(), 3000);
        }
        this.eventSource.close();
      };

      this.userInput = '';
    },
    addSystemMessage(text) {
      this.chatMessages.push({
        type: 'system',
        content: text
      });
      this.scrollToBottom();
    },
    scrollToBottom() {
      if (this.$refs.chatDialog) {
        this.$refs.chatDialog.scrollTop = this.$refs.chatDialog.scrollHeight;
      }
    }
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  }
};
</script>

<style scoped>
.menu-management {
  width: 100%;
  min-height: 100vh;
  margin: 0;
  padding: 30px;
  background-color: #fff;
  padding-bottom: 100px;
}

.pagination {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 30px;
  margin-top: 24px;
  justify-content: center;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
  padding: 16px;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 16px;
  border-top: 1px solid #ebeef5;
  background-color: #f5f7fa;
  box-shadow: none;
}

.menu-management h2 {
  margin-top: 10px;
  margin-bottom: 24px;
  font-size: 24px;
  font-weight: 500;
  text-align: left;
}

/* 优化对话框样式 */
.chat-dialog {
  border: none;
  border-radius: 12px;
  height: 500px;
  overflow-y: auto;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #f9fafb;
}

/* 优化消息样式 */
.message {
  margin-bottom: 12px;
  padding: 12px 16px;
  max-width: 70%;
  display: inline-block;
  border-radius: 16px;
  position: relative;
  font-size: 14px;
  line-height: 1.5;
}

.message.user {
  background-color: #409eff;
  color: #fff;
  float: right;
  clear: both;
  border-bottom-right-radius: 4px;
}

.message.ai {
  background-color: #fff;
  color: #303133;
  float: left;
  clear: both;
  border-bottom-left-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.message.system {
  background-color: #fdf6ec;
  color: #faad14;
  text-align: center;
  display: block;
  margin: 12px auto;
  max-width: 90%;
  border-radius: 8px;
  font-size: 12px;
}

/* 输入容器样式优化 */
.input-container {
  display: flex;
  gap: 12px;
}

.el-input {
  flex-grow: 1;
}

.el-button {
  min-width: 100px;
}

/* 突出标题样式 */
.ai-chat-page h2 {
  font-size: 32px; /* 增大字体大小 */
  color: #409eff; /* 设置标题颜色为 Element Plus 主题色 */
  font-weight: 700; /* 字体加粗 */
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1); /* 添加文字阴影 */
  margin-bottom: 32px; /* 增加标题下方的间距 */
}
</style>